package com.eshop.eshopmanagersystem.controller;

import com.eshop.eshopmanagersystem.dal.BarcodeDAL;
import com.eshop.eshopmanagersystem.dal.UserDAL;
import com.eshop.eshopmanagersystem.model.BarcodeInfo;
import com.eshop.eshopmanagersystem.model.UserInfo;
import com.eshop.eshopmanagersystem.unti.OrderData;
import com.eshop.eshopmanagersystem.unti.Response;
import com.eshop.eshopmanagersystem.unti.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * API接口服务控制器
 * 提供给超市客户端使用
 */

@RestController
public class ClientController {

    @Autowired
    BarcodeDAL bdal;

    /**
     * 提供前端查询产品数据信息
     */
    @CrossOrigin
    @RequestMapping(value = "/postProductByBarcode", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response postProductByBarcode(@RequestBody BarcodeInfo barcode){
        return new Response(200,"查询成功",bdal.getProductByBarcode(barcode));
    }

    @Autowired
    UserDAL userDAL;

    /**
     * 用户登录
     */
    @CrossOrigin
    @RequestMapping(value = "/validateClient", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response validateClient(@RequestBody UserInfo user){
        UserInfo loginuser=userDAL.validateUser(user);
        if(loginuser!=null) {
            String token = TokenUtils.sign(user);
            HashMap<String, Object> hs = new HashMap<>();
            hs.put("token", token);
            hs.put("user",user.getUsername());
            hs.put("user_id",loginuser.getUser_id());
            return new Response(200, "请求成功", hs);
        }else{
            return new Response(403,"验证失败",null);
        }
    }

    /**
     * 超市端用户端
     * 订单支付API
     */
    @CrossOrigin
    @RequestMapping(value = "/orderPayment", method = RequestMethod.POST, produces = "application/json; utf-8")
    public Response orderPayment(@RequestBody OrderData orderdata){
        System.out.println(orderdata);
        //把数据丢到数据实现层，进行数据操作
        //思路一：在Java将对象分解，分别执行sql操作
        if(bdal.addOrder(orderdata)){
            return new Response(200,"支付成功",null);
        }else {
            return new Response(500,"支付失败",null);
        }
        //思路二：将对象直接丢给存储过程，进行一体化操作
        //return new Response(200,"模拟支付成功",null);
    }

    /**
     * 测试订单生成编码
     */
    @CrossOrigin
    @RequestMapping(value = "/getordercode", method = RequestMethod.GET, produces = "application/json; utf-8")
    public String getordercode(){
        return BarcodeDAL.makeOrderCode();
    }
}
